import SwiftUI
import Kingfisher

struct DiscoverView: View {
    @State private var currentIndex: Int = 0
    @State private var scrollOffset: CGFloat = 0
    @State private var posterScale: CGFloat = 1.0
    @State private var showBackdrop: Bool = false
    @State private var imageID = UUID()  // 用来强制刷新
    @State private var hasAppeared = false
    @StateObject private var viewModel = MainPicaViewModel()
    @State private var showFloatingWindow = true
    @State private var rotationAngle: Double = 0
    

    
    var body: some View {
        NavigationStack {
            GeometryReader { proxy in
                
                ZStack(alignment: .top) {
                    LazyVStack {
                        if currentIndex >= 0 && currentIndex < viewModel.homeBanners.count {
                            // 访问数组时确保索引有效
                            CachedImageViewHeight(imageURL: viewModel.homeBanners[currentIndex].cover)
                                .scaledToFill()  // 填充模式，确保宽度按比例缩放
                                .frame(width: proxy.size.width, height: 800)  // 高度固定为800，宽度自适应
                                .clipped()  // 裁剪超出的部分
                                .offset(y: -scrollOffset > 0 ? scrollOffset : 0)
                                .scaleEffect(posterScale)
                                .animation(.easeOut(duration: 0.2), value: posterScale)
                                .id(currentIndex)  // 使用 currentIndex 来触发视图刷新
                                .onAppear {
                                    print("Image \(currentIndex) loaded")
                                }
                        }
                        
                    }
                    .frame(height:800)
                    .ignoresSafeArea(.all)
                    
                    ScrollView {
                        GeometryReader { geometry in
                            Color.clear
                                .onChange(of: geometry.frame(in: .global).minY) { oldValue, newValue in
                                    scrollOffset = newValue
                                    if newValue < 0 {
                                        posterScale = 1 + abs(newValue) / 2000  //向上滑动，图片逐渐增大
                                    } else {
                                        posterScale = min(1 + newValue / 500, 1.2)
                                    }
                                    
                                    // 限制最大缩放比例，避免过度放大
                                    if posterScale > 1.2 {
                                        posterScale = 1.2
                                    }
                                }
                        }
                        .frame(height: 0)
                        
                        ZStack(alignment: .top) {
                            TabView(selection: $currentIndex) {
                                if currentIndex >= 0 && currentIndex < viewModel.homeBanners.count {
                                    ForEach(0..<viewModel.homeBanners.count, id: \.self) { index in
                                        NavigationLink {
                                            DetailView(item: viewModel.homeBanners[index])
                                        } label: {
                                            Discovertitle(item: viewModel.homeBanners[index],index:index)
                                                .frame(width: proxy.size.width, height: 200)
                                                .tag(index)
                                        }
                                    }}
                            }
                            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))  // 隐藏分页指示器
                            .frame(width: proxy.size.width, height: 150)
                            .background(
                                LinearGradient(
                                    gradient: Gradient(colors: [Color("BgColor1").opacity(0),Color("BgColor1").opacity(0),Color("BgColor1").opacity(0.7),Color("BgColor1").opacity(0.9), Color("BgColor1").opacity(1)]),
                                    startPoint: .top,
                                    endPoint: .bottom
                                )
                            )
                            .padding(.top, 450)
                            .onChange(of: currentIndex) { oldValue, newIndex in
                                // 更新一个唯一的 UUID，用来触发图片重新加载
                                imageID = UUID()
                                triggerHapticFeedback()  // 每次索引变化时触发震动反馈
                            }
                            
                            VStack(alignment: .leading) {
                                // 自定义分页指示器
                                CustomPaginationView(currentIndex: $currentIndex, totalPages: viewModel.homeBanners.count)
                                    .frame(width:proxy.size.width)
                                    .padding(.bottom,10)
                                
                                Section {
                                    VStack(alignment: .leading) {
                                        HStack {
                                            NavigationLink {
                                                ListView(type:0,fav_type:1)
                                            } label: {
                                                HStack{
                                                    Text("HOT-热门推荐")
                                                        .foregroundStyle(.white)
                                                    Image(systemName: "chevron.right")
                                                        .foregroundStyle(.gray)
                                                        .font(.system(size: 20, weight: .medium))
                                                }.simultaneousGesture(
                                                    TapGesture().onEnded {
                                                        triggerHapticFeedback()  // 在点击时触发反馈
                                                    }
                                                )
                                            }
                                        }
                                        .font(.system(size: 22, weight: .semibold))
                                        
                                        ScrollView(.horizontal) {
                                            LazyHStack(spacing: 20) {
                                                ForEach(viewModel.homehots, id: \.id) { item in
                                                    NavigationLink {
                                                        DetailView(item: item)
                                                    } label: {
                                                        DiscoverTopCard(item: item,tag:"hot")
                                                            .frame(width: 140,height:160)
                                                    }
                                                }
                                            }
                                        }.frame(height:160)
                                    }
                                    .padding()
                                }
                                
                                Section {
                                    VStack(alignment: .leading) {
                                        HStack {
                                            NavigationLink {
                                                ListView(type:3)
                                            } label: {
                                                HStack{
                                                    Text("COMIC-漫画")
                                                        .foregroundStyle(.white)
                                                    Image(systemName: "chevron.right")
                                                        .foregroundStyle(.gray)
                                                        .font(.system(size: 20, weight: .medium))
                                                }.simultaneousGesture(
                                                    TapGesture().onEnded {
                                                        triggerHapticFeedback()  // 在点击时触发反馈
                                                    }
                                                )
                                            }
                                        }
                                        .font(.system(size: 22, weight: .semibold))
                                        
                                        ScrollView(.horizontal) {
                                            LazyHStack(spacing: 20) {
                                                ForEach(viewModel.homecomics, id: \.id) { item in
                                                    NavigationLink {
                                                        DetailView(item: item)
                                                    } label: {
                                                        DiscoverTopCard(item: item,tag:"")
                                                            .frame(width: 140,height:240)
                                                    }
                                                }
                                            }
                                        }.frame(height:240)
                                    }
                                    .padding()
                                }
                                
                                Section {
                                    VStack(alignment: .leading) {
                                        HStack {
                                            NavigationLink {
                                                ListView(type:1)
                                            } label: {
                                                HStack{
                                                    Text("VIDEO-视频")
                                                        .foregroundStyle(.white)
                                                    Image(systemName: "chevron.right")
                                                        .foregroundStyle(.gray)
                                                        .font(.system(size: 20, weight: .medium))
                                                }.simultaneousGesture(
                                                    TapGesture().onEnded {
                                                        triggerHapticFeedback()  // 在点击时触发反馈
                                                    }
                                                )
                                            }
                                        }
                                        .font(.system(size: 22, weight: .semibold))
                                        
                                        ScrollView(.horizontal) {
                                            LazyHStack(spacing: 20) {
                                                ForEach(viewModel.homevideos, id: \.id) { item in
                                                    NavigationLink {
                                                        DetailView(item: item)
                                                    } label: {
                                                        DiscoverTopCard(item: item,tag:"")
                                                            .frame(width: 140,height:140)
                                                    }
                                                }
                                            }
                                        }.frame(height:140)
                                    }
                                    .padding()
                                }
                                Section {
                                    VStack(alignment: .leading) {
                                        HStack {
                                            NavigationLink {
                                                ListView(type:2)
                                            } label: {
                                                HStack{
                                                    Text("ANIMATE-动画")
                                                        .foregroundStyle(.white)
                                                    Image(systemName: "chevron.right")
                                                        .foregroundStyle(.gray)
                                                        .font(.system(size: 20, weight: .medium))
                                                }.simultaneousGesture(
                                                    TapGesture().onEnded {
                                                        triggerHapticFeedback()  // 在点击时触发反馈
                                                    }
                                                )
                                            }
                                        }
                                        .font(.system(size: 22, weight: .semibold))
                                        
                                        ScrollView(.horizontal) {
                                            LazyHStack(spacing: 20) {
                                                ForEach(viewModel.homeanimates, id: \.id) { item in
                                                    NavigationLink {
                                                        DetailView(item: item)
                                                    } label: {
                                                        DiscoverTopCard(item: item,tag:"")
                                                            .frame(width: 140,height:140)
                                                    }
                                                }
                                            }
                                        }.frame(height:140)
                                    }
                                    .padding()
                                }
                                
                                // 其他 Section 代码省略
                            }
                            .frame(width: proxy.size.width)
                            .background(Color("BgColor1"))
                            .padding(.top, 600)
                        }.padding(.bottom,80)
                    }
                    .ignoresSafeArea(.all)
                    .scrollIndicators(.hidden) // 隐藏滚动条
                    
                    // 顶部工具栏
                    
                    VStack {
                        ZStack {
                            
                            
                            HStack {
                                //                                Button {
                                //
                                //                                } label: {
                                //                                    Image(systemName: "gear")
                                //                                        .font(.system(size: 20, weight: .bold))
                                //                                        .foregroundStyle(.white.opacity(0.8))
                                //                                }
                                //                                .padding(5)
                                //                                .background(.ultraThinMaterial)
                                //                                .clipShape(Circle())
                                
                                Spacer()
                                
                                //                                Button {
                                //
                                //                                } label: {
                                //                                    Image(systemName: "square.stack.3d.down.right")
                                //                                        .font(.system(size: 20, weight: .bold))
                                //                                        .foregroundStyle(.white.opacity(0.8))
                                //                                }
                                //                                .padding(5)
                                //                                .background(.ultraThinMaterial)
                                //                                .clipShape(Circle())
                                //
                                NavigationLink {
                                    SearchView()
                                } label: {
                                    Image(systemName: "magnifyingglass")
                                        .font(.system(size: 20, weight: .bold))
                                        .foregroundStyle(.white.opacity(0.8))
                                }
                                .padding(5)
                                .background(.ultraThinMaterial)
                                .clipShape(Circle())
                            }
                            .padding()
                            .padding(.top,40)
                            
                            Spacer()
                        }
                        .ignoresSafeArea()
                        
                        
                    }
                    //小窗
                    if showFloatingWindow {
                        SmallWin(showFloatingWindow: $showFloatingWindow)
                    }
                    
                    
                }
                .background(Color("BgColor1"))
                .frame(height: proxy.size.height)
            }
            .onAppear {
                // 确保视图出现时加载数据
                if !hasAppeared {
                    // 执行首次加载的代码
                    viewModel.get_home()
                    hasAppeared = true
                }
            }
            
        }
    }
}

#Preview {
    DiscoverView()
}
